package cn.iocoder.boot.controller.admin;

import cn.hutool.json.JSONObject;

import cn.iocoder.boot.service.BomService;
import cn.iocoder.boot.utils.ExcelToMarkdownConverter;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Controller : 控制器类
 * 用于对请求的内容、响应的内容进行数据格式转换。
 *
 */
@RestController
@Slf4j
@RequestMapping("/bomformat")
public class BomController {

    @Autowired
    private BomService bomService;

    /**
     * BOM转换
     * @param columns_relation 列映射关系
     * @param md_data markdown格式源数据
     * @param file 源文件路径
     * @return
     */
    @PermitAll
    @RequestMapping(value = "/bomConvert", method = RequestMethod.POST, produces = "application/json; text/plain; */*")
    public String bomConvert(String columns_relation, String md_data, @RequestParam("file") MultipartFile file,
                             String userId, String appKey, String source_column) throws IOException {
        log.info("收到bomConvert请求,columns_relation={},source_file={},userId={},appKey={},source_column={},md_data={}",
                columns_relation, file.getOriginalFilename(), userId, appKey, source_column, md_data);
        columns_relation = bomService.parseMixedContent(columns_relation).toString();

        JSONObject result = new JSONObject();
        result.set("code", 200);
        result.set("msg", "调用成功");
        String fileName = bomService.bomConvert(columns_relation, md_data, file, userId, appKey, source_column);
        result.set("data", fileName);
        log.info("完成bomConvert请求,fileName={}", fileName);
        if (userId.equals("dify")) {
            return "转换成功：\n" + fileName;
        }
        return result.toStringPretty();
    }

    /**
     * 根据AI传递的BOM_NO，找到对应的模板内容返回
     */
    @PermitAll
    @RequestMapping(value = "/getTemplateContent", method = RequestMethod.GET, produces = "application/json")
    public String getTemplateContent(String bom_no, String source_coloum) {
        JSONObject result = new JSONObject();
        result.set("code", 200);
        result.set("msg", "调用成功");
        String templateContent = bomService.getTemplateContent(bom_no, source_coloum);
        result.set("data", templateContent);
        log.info("完成getTemplateContent请求,templateContent={}", templateContent);
        return result.toStringPretty();
    }
    /**
     * 给业务开发调用Dify 工作流的接口
     */
    @PermitAll
    @RequestMapping(value = "/runBomFormatWF", method = RequestMethod.GET, produces = "application/json")
    public String runBomFormatWF(@RequestParam("file") MultipartFile file, String bom_no) {
        JSONObject result = new JSONObject();
        result.set("code", 200);
        result.set("msg", "调用成功");
        String templateContent = bomService.getTemplateContent(bom_no, "");
        result.set("data", templateContent);
        log.info("完成getTemplateContent请求,templateContent={}", templateContent);
        return result.toStringPretty();
    }

    /**
     * Excel文件转md文本（不如Dify中markdown工具好用）
     * @param file
     * @return
     * @throws IOException
     */
    @PermitAll
    @RequestMapping(value = "/excel2md", method = RequestMethod.POST, produces = "application/json; text/plain; */*")
    public String excel2md(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("收到excel2md请求：file={}", file.getOriginalFilename());
        String result = ExcelToMarkdownConverter.convertExcelToMD(file);
        log.info("完成excel2md请求：file={}", result);
        return result;
    }

    /**
     * 获取建议配置等文件
     */
    @PermitAll
    @RequestMapping(value = "/getRelationConfig", method = RequestMethod.GET, produces = "application/json")
    public String getRelationConfig(String configName) {
        log.info("收到getRelationConfig请求,configName={}", configName);
//        JSONObject result = new JSONObject();
//        result.set("code", 200);
//        result.set("msg", "调用成功");
        String templateContent = bomService.getJsonObjCfg(configName).toStringPretty();
//        result.set("data", templateContent);
        log.info("完成getTemplateContent请求,templateContent={}", templateContent);
        return templateContent;
    }
    /**
     * 校验映射后的columns_relation是否正确，正确返回“校验OK”
     */
    @PermitAll
    @RequestMapping(value = "/checkConvert", method = RequestMethod.GET, produces = "application/json; text/plain; */*")
    public String checkConvert(String columns_relation) {
        log.info("收到checkConvert请求,columns_relation={}", columns_relation);
        String result = bomService.checkConvert(columns_relation);
        log.info("完成checkConvert请求,result={}", result);
        return result;
    }
    /**
     * 取所有模板，用于相似度比较（暂未使用）
     */
//    @RequestMapping(value = "/getAllTemplate", method = RequestMethod.GET, produces = "application/json")
//    public String getAllTemplate(String bom_no, String source_coloum) {
//        JSONObject result = new JSONObject();
//        result.set("code", 200);
//        result.set("msg", "调用成功");
//        String templateContent = bomService.getTemplateContent(bom_no, source_coloum);
//        result.set("data", templateContent);
//        log.info("完成getTemplateContent请求,templateContent={}", templateContent);
//        return result.toStringPretty();
//    }


    @PermitAll
    @RequestMapping(value = "/analysis", method = RequestMethod.POST)
    public CommonResult<String> analysis(@RequestParam("fileurl") String fileurl, @RequestParam("id") String id,@RequestParam(value = "env",required = false) String env) throws IOException {

        log.info("收到analysis请求：id:"+id+",fileurl:"+fileurl+",env:"+env);

        bomService.analysis(fileurl,id,env);
        log.info("完成analysis请求");


        return CommonResult.success("成功");



    }



}
